/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core.tags;

import com.farent.solutions.plugins.stripes.hyperstripes.utils.Utils;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author farouka
 */
public class TagUtils {

    public static String getNameNoPrefix(String tagWithPrefix) {
        if (tagWithPrefix.contains(":")) {
            String[] split = tagWithPrefix.split(":");
            tagWithPrefix = split[1];
        }
        return tagWithPrefix;
    }

    /**
     * Formats a given XML/HTML tag properly aligning the nested tags
     * The tag must be a valid XML/HTML tag which is properly closed
     * @param input
     * @param indentLevel the level of indent to start it from. 0 = no indent
     * @return
     */
    public static String formatTag(String input, int indentLevel) {
        Writer out = new StringWriter();
        try {
            final Document document = parseXmlString(input);
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            serializer.transform(new DOMSource(document), new StreamResult(out));


        } catch (TransformerException ex) {
            Logger.getLogger(TagUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return out.toString();
//        return cleanTag(input);
    }

    private static Document parseXmlString(String in) {
        try {
            in = cleanTag(in);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static String cleanTag(String in) {
            StringBuilder builder = new StringBuilder();

        try {
            Scanner scanner = new Scanner(in);
            while(scanner.hasNextLine())
            {
                String line = scanner.nextLine();
                String replaceAll = line.replaceAll("^[ \t]+|[ \t]+$", Utils.EMPTY_STRING);
                replaceAll = replaceAll.replaceAll("[\\s]+", " ");
                builder.append(replaceAll);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        builder.trimToSize();
        return builder.toString();
    }
}
